<template>
  <a-card :bordered="false" :loading="loading">
    <DynamicForm
      :data-source="dataColumn"
      :model-data="{
        ...detailData,
        permissions: {
          checked: detailData?.permissions?.split(',').flatMap((item) => parseInt(item)),
        },
      }"
      @submit-form="submitForm"
      @cancel="closeTab"
    ></DynamicForm>
  </a-card>
</template>

<script setup lang="tsx">
  import { message } from 'ant-design-vue';
  import DynamicForm from '@/components/dynamicForm/index.vue';
  import useRequestDetail from '@/hooks/useRequestDetail';
  import { createRole, sysRoleApi, updateRole } from '@/api/system/role';
  import { useTabsViewStore } from '@/store/modules/tabsView';
  import { ComponentsTypeEnum } from '@/enums/componentsEnum';
  import { getSysPermissionTree } from '@/api/system/permission';

  defineOptions({
    name: 'roleDetail',
  });
  const route = useRoute();
  const tabsViewStore = useTabsViewStore();
  const treeData = ref<{ [x: string]: any }[]>([]);
  const dataColumn = ref([
    {
      field: 'roleName',
      component: ComponentsTypeEnum.Input,
      label: '角色名称',
      rules: [{ required: true }],
    },
    {
      field: 'key',
      component: ComponentsTypeEnum.Input,
      label: 'key',
      rules: [{ required: true }],
    },
    {
      field: 'remark',
      component: ComponentsTypeEnum.InputTextarea,
      label: '备注',
    },
    {
      field: 'permissions',
      component: ComponentsTypeEnum.Tree,
      label: '所拥有的权限',
      componentProps: {
        checkable: true,
        treeData,
        fieldNames: { key: 'id' },
      },
      rules: [
        {
          required: true,
          validator: (rule, value) => {
            if (!value) {
              return Promise.reject('请勾选所拥有的权限');
            }
            return Promise.resolve();
          },
        },
      ],
    },
  ]);
  const { detailData, loading } = useRequestDetail({
    apiKey: sysRoleApi.sysRoleDetail,
    initParams: route?.query,
    isMount: !!Object.values(route?.query).length && !!Object.values(route?.query)[0],
  });
  const getPermissionTree = async () => {
    const data = await getSysPermissionTree();
    if (data) {
      treeData.value = data;
    } else {
      treeData.value = [];
    }
  };

  const submitForm = async (params) => {
    const roleId = route?.query?.id;
    const selectedPermissions = params.permissions?.checked || params.permissions;
    if (!selectedPermissions.length) {
      message.error('请勾选至少一个权限');
      return;
    }
    params.permissions = selectedPermissions.join(',');
    const res = roleId ? await updateRole({ ...params, id: roleId }) : await createRole(params);
    if (res) {
      message.success(res?.msg);
      closeTab();
    }
  };

  const closeTab = () => {
    tabsViewStore.closeCurrentTab(route);
  };
  onMounted(async () => await getPermissionTree());
</script>

<style></style>
